// ignore: depend_on_referenced_packages
import 'dart:io';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:dio_cache_interceptor/dio_cache_interceptor.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter/foundation.dart';
import 'app_dio_config.dart';

class AppDioService with DioMixin implements Dio {
  AppDioService({BaseOptions? options, AppDioConfig? dioConfig}) {
    options ??= BaseOptions(
      baseUrl: dioConfig?.baseUrl ?? "",
      contentType: 'application/json',
      connectTimeout:
          Duration(milliseconds: dioConfig?.connectTimeout ?? 10000),
      sendTimeout: Duration(milliseconds: dioConfig?.sendTimeout ?? 10000),
      receiveTimeout:
          Duration(milliseconds: dioConfig?.receiveTimeout ?? 10000),
    )..headers = dioConfig?.headers;
    this.options = options;

    // DioCacheManager
    final cacheOptions = CacheOptions(
      // A default store is required for interceptor.
      store: MemCacheStore(),
      // Optional. Returns a cached response on error but for statuses 401 & 403.
      hitCacheOnErrorExcept: [401, 403],
      // Optional. Overrides any HTTP directive to delete entry past this duration.
      maxStale: const Duration(days: 7),
    );
    interceptors.add(DioCacheInterceptor(options: cacheOptions));
    // Cookie管理
    if (dioConfig?.cookiesPath?.isNotEmpty ?? false) {
      // PersistCookieJar
      interceptors.add(CookieManager(
          PersistCookieJar(storage: FileStorage(dioConfig!.cookiesPath))));
    }

    if (kDebugMode) {
      interceptors.add(LogInterceptor(
          responseBody: true,
          error: true,
          requestHeader: false,
          responseHeader: false,
          request: false,
          requestBody: true));
    }
    if (dioConfig?.interceptors?.isNotEmpty ?? false) {
      interceptors.addAll(dioConfig!.interceptors!);
    }
    httpClientAdapter = IOHttpClientAdapter();
    if (dioConfig?.proxy?.isNotEmpty ?? false) {
      setProxy(dioConfig!.proxy!);
    }
    // httpClientAdapter = DefaultHttpClientAdapter();
    // if (dioConfig?.proxy?.isNotEmpty ?? false) {
    //   setProxy(dioConfig!.proxy!);
    // }
  }
  setProxy(String proxy) {
    (httpClientAdapter as IOHttpClientAdapter).createHttpClient = () {
      final client = HttpClient();

      client.findProxy = (uri) {
        return 'PROXY $proxy';
      };
      return client;
    };
  }
  // setProxy(String proxy) {
  //   (httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
  //       (client) {
  //     // config the http client
  //     client.findProxy = (uri) {
  //       // proxy all request to localhost:8888
  //       return "PROXY $proxy";
  //     };
  //     // you can also create a HttpClient to dio
  //     // return HttpClient();
  //   };
  // }
}
